package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.GoodsEntity;
import com.quanshu.exchange.support.entity.ShoppingCarEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.web_page.SettleAccountActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 购物车
 * Created by jye on 2018/2/1.
 */

public class ShoppingCartActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.edit_comment)
    TextView editComment;
    @BindView(R.id.shop_trolley_null)
    LinearLayout shopTrolleyNull;
    @BindView(R.id.shop_trolley_recy)
    RecyclerView shopTrolleyRecy;
    @BindView(R.id.shop_trolley_all_image)
    ImageView shopTrolleyAllImage;
    @BindView(R.id.shop_trolley_all_llt)
    LinearLayout shopTrolleyAllLlt;
    @BindView(R.id.shop_trolley_total_price)
    TextView totalPrice;
    @BindView(R.id.shop_trolley_zongji_llt)
    LinearLayout shopTrolleyZongjiLlt;
    @BindView(R.id.shop_trolley_delete)
    TextView shopTrolleyDelete;

    private DecimalFormat df = new DecimalFormat("0.00");//转化成为两位小数;
    private SingleAdapter<GoodsEntity> adapter;

    private List<GoodsEntity> allDatas;

    private boolean isCheckAll = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_trolley);
        ButterKnife.bind(this);
    }

    private void initView() {
        shopTrolleyRecy.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<GoodsEntity>(this,
                R.layout.item_shop_trolley) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<GoodsEntity> wrapper,
                                 GoodsEntity item,
                                 int position) {

                item.setTwo_price(String.valueOf(Double.valueOf(item.getSell_price()) * 2));

                holder.setImageUrl(R.id.shop_trolley_shop_image,
                        Config.URL_HOST_SHOP + item.getImg(),
                        R.drawable.default_avatar);
                holder.setText(R.id.shop_trolley_shop_name, item.getName());
                holder.setText(R.id.shop_trolley_shop_bianhao, "商品编号：" + item.getGoods_no());
                holder.setText(R.id.shop_trolley_shop_price_j, item.getSell_price());
                holder.setText(R.id.shop_trolley_shop_price_r, "￥" + item.getSell_price());
                TextView shopPriceR = holder.getView(R.id.shop_trolley_shop_price_r);
                shopPriceR.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.setText(R.id.shop_trolley_shop_number, "x" + item.getCount());

                //商品数量 - 增 - 减
                holder.setOnClickListener(R.id.shop_trolley_shop_edit, view -> {
                    doShowDialog(item, position);
                });

                ImageView imageView = holder.getView(R.id.shop_trolley_select_image);

                if (item.isSelectState()) {
                    imageView.setSelected(true);

                    for (GoodsEntity entity : allDatas) {
                        if (!entity.isSelectState()) {
                            isCheckAll = false;
                            shopTrolleyAllImage.setSelected(isCheckAll);
                            break;
                        } else {
                            isCheckAll = true;
                            shopTrolleyAllImage.setSelected(isCheckAll);
                        }
                    }

                } else {
                    imageView.setSelected(false);
                    isCheckAll = false;
                    shopTrolleyAllImage.setSelected(isCheckAll);
                }

                //只要有一个item处于勾选状态，“去结算” 文字就高亮
                for (GoodsEntity entity : allDatas) {

                    if (entity.isSelectState()) {
                        shopTrolleyDelete.setBackgroundColor(Color.parseColor("#F8DCB0"));
                        break;
                    } else if (!entity.isSelectState()) {
                        shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                    }
                }

                //勾选商品
                holder.getView(R.id.all_shop_trolley).setOnClickListener(view -> {
                    if (item.isSelectState()) {
                        item.setIs_service("0");
                        item.setSelectState(false);
                        holder.getView(R.id.mianfei_price).setVisibility(View.GONE);
                        isCheckAll = false;
                    } else {
                        item.setSelectState(true);
                    }
                    adapter.notifyDataSetChanged();
                    setTotalPrice();
                });

                ImageView isGetFreeBtn = holder.getView(R.id.mianfei_image);
                if (item.getIs_service() != null && item.getIs_service().equals("1")) {
                    isGetFreeBtn.setSelected(true);
                } else {
                    isGetFreeBtn.setSelected(false);
                }
                //勾选免费
                holder.getView(R.id.mianfei_select).setOnClickListener(view -> {
                    // 如果没有选择该商品
                    if (!item.isSelectState()) {
                        ToastHelper.toast("请先勾选此商品");
                        return;
                    } else {
                        if (item.getIs_service() != null && item.getIs_service().equals("1")) {
                            item.setIs_service("0");
                            holder.getView(R.id.mianfei_price).setVisibility(View.GONE);
                        } else {
                            item.setIs_service("1");
                            holder.getView(R.id.mianfei_price).setVisibility(View.VISIBLE);
                            holder.setText(R.id.mianfei_price, "+" + item.getSell_price());
                        }
                        adapter.notifyDataSetChanged();
                    }
                    setTotalPrice();
                });
            }
        });
        shopTrolleyRecy.setAdapter(adapter);
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        //点 “编辑”去删除页面
        RxViewHelper.getInstance().clicks(editComment, aVoid -> {

            Intent intent = new Intent(ShoppingCartActivity.this, ShopCartDeleteActivity.class);
            startActivity(intent);

        });

        //点击全选
        RxViewHelper.getInstance().clicks(shopTrolleyAllLlt, aVoid -> doCheckAll());

        //去结算
        RxViewHelper.getInstance().clicks(shopTrolleyDelete, aVoid -> goCloseAnAccount());
    }

    //前往结算页面
    private void goCloseAnAccount() {
        //做结算操作时，须将String[]转为json字符串
        Gson gson = new Gson();
        String goodsIdTypeNumsServiceString = gson.toJson(getGoodsIdTypeNumsServiceArray());
        Log.e("888888888", goodsIdTypeNumsServiceString);
        Intent intent = new Intent(ShoppingCartActivity.this, SettleAccountActivity.class);
        intent.putExtra("SETTLE_ACCOUNT", goodsIdTypeNumsServiceString);
        startActivity(intent);
    }


    private String[] goodsIdTypeNumsServiceArray;

    //用于结算
    private String[] getGoodsIdTypeNumsServiceArray() {

        ArrayList<String> goodsId = new ArrayList<String>();
        if (allDatas != null && allDatas.size() > 0) {
            for (GoodsEntity goodsEntity : allDatas) {
                if (goodsEntity.isSelectState()) {

                    if (goodsEntity.getGoods_type().equals("goods")) {
                        goodsId.add(goodsEntity.getGoods_id() + "," +
                                goodsEntity.getGoods_type() + "," +
                                goodsEntity.getCount() + "," +
                                goodsEntity.getIs_service());
                    } else {
                        goodsId.add(goodsEntity.getProduct_id() + "," +
                                goodsEntity.getGoods_type() + "," +
                                goodsEntity.getCount() + "," +
                                goodsEntity.getIs_service());
                    }
                }
            }
            goodsIdTypeNumsServiceArray = goodsId.toArray(new String[goodsId.size()]);
        }
        return goodsIdTypeNumsServiceArray;
    }

    //全选
    private void doCheckAll() {
        if (adapter != null && allDatas != null && allDatas.size() > 0) {
            isCheckAll = !isCheckAll;
            shopTrolleyAllImage.setSelected(isCheckAll);
            for (GoodsEntity goodsEntity : allDatas) {
                if (isCheckAll == true) {
                    goodsEntity.setSelectState(true);
                } else {
                    goodsEntity.setSelectState(false);
                }
            }
            setTotalPrice();
            adapter.notifyDataSetChanged();
        }
    }

    //初始化数据
    private void initData() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getMyCart(AppUtils.getSignParams(String.valueOf(currentUser.getId())), String.valueOf(currentUser.getId()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<ShoppingCarEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ShoppingCarEntity> response) {
                        if (response.getData() != null && response.getData().getGoodsList().size() > 0) {
                            shopTrolleyNull.setVisibility(View.GONE);
                            allDatas = response.getData().getGoodsList();
                            adapter.setData(allDatas);
                        } else {
                            shopTrolleyNull.setVisibility(View.VISIBLE);
                            shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                            shopTrolleyAllImage.setSelected(false);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    //商品数量 加 - 减 dialog
    private void doShowDialog(GoodsEntity item, int position) {
        DialogAddReduce dialogAddReduce = new DialogAddReduce(this);
        dialogAddReduce.show();
        dialogAddReduce.setNums(item.getCount());

        //确定
        dialogAddReduce.getOneBehaviorSubject().subscribe(num -> {
            getIncreCart(item, num, position);
            dialogAddReduce.dismiss();
        });
    }

    //计算总价
    private void setTotalPrice() {
        if (allDatas != null && allDatas.size() > 0) {
            double price = 0.00;
            double zongPrice = 0.00;
            for (GoodsEntity goodsEntity : allDatas) {
                if (goodsEntity.isSelectState()) {
                    double currentPrice = Double.valueOf(goodsEntity.getSell_price());
                    if (goodsEntity.getIs_service() != null && goodsEntity.getIs_service().equals("1")) {
                        currentPrice = currentPrice * 2;
                    }
//                    price += currentPrice;
                    zongPrice += currentPrice * goodsEntity.getCount();
//                    zongPrice += price;
                }
            }
            totalPrice.setText("总计：￥" + df.format(zongPrice));
        }
    }


    /**
     * 购买车商品数量增加或者减少 - 增加or减少
     *
     * @param item
     * @param value ​增加或减少的数量
     */
    private void getIncreCart(GoodsEntity item, int value, int position) {

        String shop_id = null;
        String shop_type = null;

        if (item.getGoods_type().equals("goods")) {

            shop_id = item.getGoods_id();
        } else {

            shop_id = item.getProduct_id();
        }
        shop_type = item.getGoods_type();

        NetClient.getInstance().getShopService(ShopInterface.class)
                .getIncreCart(AppUtils.getSignParams(String.valueOf(currentUser.getId()), shop_id, shop_type, value + "")
                        , String.valueOf(currentUser.getId()), shop_id, shop_type, value)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {

                        item.setCount(value);

                        if (adapter != null) {
                            List<GoodsEntity> data = adapter.getData();
                            data.set(position, item);
                            adapter.notifyDataSetChanged();
                            setTotalPrice();
                        }

                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
        initView();
        initListener();
        initData();
        totalPrice.setText("总计：￥" + df.format(0.00));
    }
}
